package servlet;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import dbOperator.*;

/**
 * Servlet implementation class ModifyAdminPassword
 */
@WebServlet("/ModifyAdminPassword")
public class ModifyAdminPassword extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ModifyAdminPassword() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//
		response.setContentType("text/html; charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		request.setCharacterEncoding("UTF-8");
		//ܱ
		String newpasswd = (String) request.getParameter("newpasswd");
		String oldpasswd = (String) request.getParameter("confirmpwd");
		Cookie cookies[] = request.getCookies();
		if(cookies == null) {return;}
		String currentCookie = new String();
		for(Cookie c : cookies) {
			if(c.getName().equals("LoginInfo")) {
				currentCookie = c.getValue();
			}
		}
		try {
			int updaterUid = AdvancedOperation.getUidbyCookie(currentCookie);
			if(AdvancedOperation.getIdentity(updaterUid) == 1) {
				AdvancedOperation.changePassword(updaterUid, updaterUid, oldpasswd, newpasswd);
				request.getSession().invalidate();
				response.sendRedirect("adminindex.html");
			}
		} catch (SQLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
